<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>知云——针对编程的个性化学习推荐系统</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>

    <c:if test="${empty user}">
        <%--用户未登录，不能写博客--%>
        <jsp:forward page="/login"/>
    </c:if>

    <base href="${APP_PATH}">
    <link rel="shortcut icon" type="image/x-icon" href="${APP_PATH}/static/favicon.ico"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/toastr.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/offcanvas.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/fontawesome.min.css">


    <link rel="stylesheet" href="${APP_PATH}/static/css/pell.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/input-image-upload.css">

</head>
<style>
    /*限定图片大小样式*/
    div[contenteditable='true'] img {
        width: 100%;
        overflow: hidden;
    }
</style>

<body>

<jsp:include page="${APP_PATH}/common/head-blog.jsp"/>

<%--用户个人博客管理页面--%>
<c:choose>
    <c:when test="${not empty user}">
        <%--用户已登陆--%>
        <div class="mt-2 col-sm-12 col-md-12 col-lg-9" id="defaultDiv" data-id="${user.id}" data-areaid="${blog.areaid}"
             data-blogtypeid="${blog.blogtypeid}"
             style="margin-left: auto;margin-right: auto;">
            <div class="d-flex p-3 bg-white mb-2 rounded shadow-sm">
                <div class="flex-fill text-center"><a href="/blog-all" class="text-dark"><i
                        class="fa fa-paper-plane"></i>文章管理</a>
                </div>
                <div class="flex-fill text-center"><a href="/blog-type" class="text-dark"><i class="fa fa-table"></i>类别管理</a>
                </div>
                <div class="flex-fill text-center"><a href="/blog-comment" class="text-dark"><i
                        class="fa fa-comments"></i>评论管理</a></div>
                <div class="flex-fill text-center"><a href="#" class="text-danger"><i
                        class="fa fa-arrow-circle-right"></i>写文章</a></div>
            </div>
            <div class="bg-white p-3 rounded shadow-sm">
                <form id="blogForm">
                        <%--id--%>
                    <input type="hidden" id="id" name="id" value="${blog.id}"/>
                        <%--文章标题--%>
                    <h5 class="border-bottom border-gray pb-2 mb-2">
                        <input id="blogtitle" name="blogtitle" type="text" class="col-12 form-control"
                               maxlength="70" placeholder="输入文章标题" value="${blog.blogtitle}">
                    </h5>
                        <%--内容--%>
                    <div id="editor" class="pell"></div>
                    <input type="hidden" id="blogcontent" name="blogcontent">
                    <div id="html-output" style="display: none"></div>
                    <div class="mt-2 form-inline">
                            <%--文章类别：获取用户博客类别--%>
                        <label for="blogtypeid">文章类别:&nbsp;&nbsp;</label>
                        <select id="blogtypeid" name="blogtypeid" class="custom-select-sm form-control col-3 col-sm-2">
                        </select>
                    </div>
                    <div class="mt-2 form-inline">
                            <%--文章领域：获取领域--%>
                        <label for="areaid">文章领域:&nbsp;&nbsp;</label>
                        <select id="areaid" name="areaid" class="custom-select-sm form-control col-3 col-sm-2">
                        </select>
                    </div>
                    <div class="mt-2">
                        <a id="btn-submit-blog" class="btn btn-sm btn-outline-primary">修改博客</a>
                    </div>
                </form>
            </div>
        </div>
    </c:when>
    <c:otherwise>
        <%--没有登录，提示用户--%>
        <div class="offset-lg-4 col-lg-4 col-md-12 col-sm-12">
            <div class="alert-warning p-3">
                <h4>您还没有登录，请先<a href="/login">登录</a></h4>
            </div>
        </div>
    </c:otherwise>
</c:choose>

<%--图片上传弹出层--%>
<div id="imageUploadDiv"
     class="bg-light rounded border border-danger border-1 shadow-lg p-3"
     style="display: none;z-index: 99;top: 15%;left: 0;right: 0;width: 200px;margin-left:auto;margin-right:auto;position: fixed;">
    <form>
        <div class="form-group">
            <label for="uploaderInput">请选择你要上传的图片:</label>
            <div style="clear: both"></div>
            <div class="input-image-uploader">
                <ul class="input-image-files pl-0" id="uploaderFiles">

                </ul>
                <div class="input-image-box">
                    <input id="uploaderInput" class="input-image" type="file" name="files" accept="image/*">
                </div>
            </div>
            <div style="clear: both"></div>
        </div>
        <div>
            <span id="imgDivInfo">点击图片预览或修改</span>
        </div>
    </form>
    <a id="btn-submit" class="btn btn-sm btn-outline-info disabled">上传</a>
    <a id="btn-cancel" class="btn btn-sm btn-light">取消</a>
</div>

<%--图片预览层--%>
<div class="my-gallery" id="gallery">
    <span class="my-gallery-img" id="galleryImg"></span>
    <div class="my-gallery-option">
        <a href="javascript:void(0);" class="my-gallery-option-icon pt-2 pb-1">
            <i id="icon-delete" class="fa fa-trash-alt fa-2x" style="color: white"></i>
        </a>
    </div>
</div>


<script src="${APP_PATH}/static/js/jquery-3.3.1.min.js"></script>
<script src="${APP_PATH}/static/js/bootstrap.min.js"></script>
<script src="${APP_PATH}/static/js/toastr.min.js"></script>
<script src="${APP_PATH}/static/js/offcanvas.js"></script>
<script src="${APP_PATH}/static/js/pell.min.js"></script>

<script>
    //点击图片上传功能
    function alertImageUploadDiv() {
        $("#imageUploadDiv").show();
    }

    $(function () {
        //pell容器初始化
        var editor = window.pell.init({
            element: document.getElementById('editor'),
            defaultParagraphSeparator: 'p',
            onChange: function (html) {
                document.getElementById('html-output').textContent = html
            }
        });

        //去掉拼写检查
        $(".pell-content").attr("spellcheck", "false");
        $(".pell-content").addClass("bg-white");

        //设置重新编辑时，编辑器中的内容
        if ($("#id").val().length === 16) {
            //重新编辑，获取该博客的内容
            var blogId = $("#id").val();
            $.ajax({
                url: '/getBlogById/' + blogId,
                type: 'GET',
                success: function (result) {
                    if (result.code === 100) {
                        var $content = $("<div>").append(result.extend.blog.blogcontent);
                        $("#blogcontent").val(result.extend.blog.blogcontent);
                        $(".pell-content").append($content);
                        //光标定位
                        var selection = getSelection();
                        // 创建新的光标对象
                        var range = document.createRange();
                        // 光标位置定位在表情节点的最大长度
                        range.setStart($content.get(0), $content.length);
                        // 使光标开始和光标结束重叠
                        range.collapse(true);
                        // 清除选定对象的所有光标对象
                        selection.removeAllRanges();
                        // 插入新的光标对象
                        selection.addRange(range);
                    } else {
                        window.location.href = '/login';
                    }
                }
            });
        }

        //点击取消按钮
        $("#btn-cancel").click(function () {
            $("#imageUploadDiv").hide();
        });

        //图片上传
        var $gallery = $("#gallery"),
            $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles");
        var lil = "";

        //添加图片
        $uploaderInput.on("change", function (e) {
            var src;  //用于图片显示的地址
            var url = window.URL || window.webkitURL || window.mozURL;  //本地地址，用于图片显示的绝对地址
            var files = e.target.files;  //选取的图片文件
            var file = files[0];
            // 过滤掉非图片类型文件
            if (file.type.match('image.*')) {
                if (url) {
                    src = url.createObjectURL(file);
                } else {
                    src = e.target.result;
                }
                var tmpl = '';
                //动态创建li标签，用于显示符合的图片
                tmpl += '<li class="input-image-file"' + 'id="' + file.name + '" style="background-image:url(' + src + ')"></li>';
                $uploaderFiles.append(tmpl);
                ++lil;  //把创建的li标签加1，用于判断图片是否到达规定数目
            }
            //做判断，如果图片达到9张
            if (lil >= 1) {
                //选中1张图片
                $('.input-image-box').css('display', 'none');
                $("#btn-submit").attr("data-flag", "true");
                $("#btn-submit").removeClass("disabled");
            } else {
                $('.input-image-box').css('display', 'block');
            }

        });


        var index;
        var tid;

        /*预览图片*/
        $uploaderFiles.on("click", "li", function () {
            index = $(this).index();
            tid = $(this).attr("id");
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });

        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $("#icon-delete").click(function () {
            $("#uploaderInput").val('');
            //删除该图片的节点
            $uploaderFiles.find("li").eq(index).remove();
            --lil;   //存储li标签的个数减1
            //做判断，如果图片到达9张

            $('.input-image-box').css('display', 'block');
            //修改保存按钮属性
            $("#btn-submit").attr("data-flag", "false");
            $("#btn-submit").addClass("disabled");
        });

        //上传图片
        $("#btn-submit").click(function () {
            //上传图片
            if ($("#btn-submit").attr('data-flag') === "true") {
                //js获取图片对象
                var formFile = new FormData();
                formFile.append("files", document.getElementById("uploaderInput").files[0]);
                $.ajax({
                    url: "/filesUpload",
                    data: formFile,
                    type: "POST",
                    dataType: "json",
                    cache: false,//上传文件无需缓存
                    processData: false,//用于对data参数进行序列化处理 这里必须false
                    contentType: false, //必须
                    success: function (result) {
                        //接收返回的图片路径
                        if (result.code === 100) {
                            //图片上传成功，result.extend.fileList.index0
                            //1.去掉输入框中的文件缓存
                            $("#uploaderInput").val('');
                            //删除该图片的节点
                            $uploaderFiles.find("li").remove();
                            $('.input-image-box').css('display', 'block');
                            //修改按钮属性
                            $("#btn-submit").attr("data-flag", "false");
                            $("#btn-submit").addClass("disabled");
                            //2.将图片插入div中
                            var url = result.extend.fileList.index0;
                            //光标返回到原来编辑的位置
                            $("div[contenteditable='true']").focus();
                            //开始插入图片
                            document.execCommand('InsertImage', false, url);
                            //3.隐藏上传图片框
                            $("#imageUploadDiv").hide();
                            toastr.success("图片上传成功！");
                        } else {
                            toastr.success("图片上传失败，请重试！！！");
                        }
                    }
                })
            } else {
                toastr.error("请先选择图片");
            }
        });


        //两个下拉框
        //博客类型
        //发送异步请求
        $.ajax({
            url: '/getAllUserBlogType',
            data: '',
            type: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    //成功获取,验证非空
                    if (result.extend.userBlogTypeList.length > 0) {
                        $("#blogtypeid").empty();
                        //插入到select中
                        //获取之前选取的blogtypeid
                        var blogtypeid = $("#defaultDiv").attr("data-blogtypeid");
                        $.each(result.extend.userBlogTypeList, function (index, item) {
                            var $option;
                            //判断是否为之前选择的那个
                            if (blogtypeid === item.id) {
                                $option = $("<option selected value='" + item.id + "'>").append(item.blogtypename);
                            } else {
                                $option = $("<option value='" + item.id + "'>").append(item.blogtypename);
                            }
                            $option.appendTo($("#blogtypeid"));
                        })
                    } else {
                        toastr.info("你尚未创建博客类别！");
                    }
                } else {
                    toastr.error("获取博客类别失败，请重新登录后重试！");
                }
            }
        });

        //领域选择
        $.ajax({
            url: "/allArea",
            method: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    $("#areaid").empty();
                    //插入到select中
                    var areaid = $("#defaultDiv").attr("data-areaid");
                    $.each(result.extend.areas, function (index, item) {
                        var $option;
                        if (areaid === item.id) {
                            $option = $("<option selected value='" + item.id + "'>").append(item.areaname);
                        } else {
                            $option = $("<option value='" + item.id + "'>").append(item.areaname);
                        }
                        $option.appendTo($("#areaid"));
                    })
                } else {
                    //获取信息失败
                    toastr.error("获取领域失败，请重新登录！！");
                }
            }
        });
    });

    //点击提交按钮
    $("#btn-submit-blog").click(function () {
        //表单校验
        var blogtitle = $("#blogtitle").val();
        if (blogtitle.length > 70 || blogtitle.length < 2) {
            toastr.error("请输入字符长度为2-70的标题！");
            return false;
        }
        var blogtypeid = $("#blogtypeid").val();
        if (!blogtypeid) {
            toastr.error("请选择文章类型！");
            return false;
        }
        var areaid = $("#areaid").val();
        if (!areaid) {
            toastr.error("请选择文章领域！");
            return false;
        }

        var $html_out = $("#html-output");
        var $blogcontent = $("#blogcontent");
        var content = $html_out.text();
        if (content) {
            $blogcontent.val($html_out.text());
        }
        //开始提交
        $.ajax({
            url: '/updateBlog',
            data: $("#blogForm").serialize(),
            type: 'POST',
            success: function (result) {
                if (result.code === 100) {
                    //跳转到查看博客页面
                    window.location.href = '/blog/' + result.extend.blogId;
                    toastr.success("修改文章成功！！");
                } else {
                    toastr.error("修改文章失败！！");
                }
            }
        });
    });

</script>

</body>

</html>
